package me.pplay.playtalk.net;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import me.pplay.playtalk.bean.ChattingRecord;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.protocol.DataCallBack;
import me.pplay.playtalk.protocol.TpChat;
import me.pplay.playtalk.util.LogManager;
import me.pplay.playtalk.util.MD5;


public class HttpUtil {
	private static final int TIMEOUT = 40 * 1000;
	public static final int UNABLE_TO_GET_FILESIZE  = 20;
	public static final int GET_FILE_ERR			= 21;
	public static final int GET_FILE_OK			= 22;
	
	public static InputStream doGet(String url){
		if(url == null || url.equals(""))
			return null;
		InputStream inputStream = null;
		try {
			URL uri = new URL(url);
			HttpURLConnection conn = (HttpURLConnection)uri.openConnection();
			setConn(conn);
			int stateCode = conn.getResponseCode();
			LogManager.LogShow("HTTPUTIL", "httpURLConnection stateCode:" + stateCode, LogManager.INFO);
			inputStream = conn.getInputStream();
		} catch (MalformedURLException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
		return inputStream;
	}
	
	public static void doGet(ChattingRecord chat, TpChat tpChat, DataCallBack callBack){
		int filezise 	= 0;
		HttpURLConnection conn 	= null;
		InputStream is			= null;
		try {
			//tpchat.tp_chat_gethttpaddr_data(servid);
			String httpUrl			= "http://" + tpChat.tp_chat_gethttpaddr_data(chat.server_id) + "/" + chat.fpath;
			URL uri 				= new URL(httpUrl);
			conn 					= (HttpURLConnection)uri.openConnection();
			setConn(conn);
			int stateCode 			= conn.getResponseCode();
			if(stateCode != 200){
				callBack.Callback(GET_FILE_ERR, null, null);
				return;
			}
			is						= conn.getInputStream();
			if(is == null){
				callBack.Callback(GET_FILE_ERR, null, null);
				return;
			}
				
//			filezise 				= Integer.parseInt(conn.getHeaderField("Content-Length"));
			filezise				= conn.getContentLength();
//			filezise				= chat.filelength;
			if(filezise <= 0){
				callBack.Callback(UNABLE_TO_GET_FILESIZE, null, null);
				return;
			}
			String fname			= getFilePath(chat, httpUrl);
			if(fname.equals("")){
				callBack.Callback(UNABLE_TO_GET_FILESIZE, null, null);
				return;
			}
//			FileUtil.createFile(fname);
			FileOutputStream fos	= new FileOutputStream(fname);
			byte buf[]				= new byte[1024];
			int downLoadFileSize	= 0;
			int numread				= 0;
			while((numread = is.read(buf)) != -1){
				if(!chat.isDownd)break;
				fos.write(buf, 0, numread);
				downLoadFileSize += numread;
				int progress 	  = downLoadFileSize*100 / filezise;
				callBack.Callback(GET_FILE_OK, null, (Object)progress);
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			conn = null;
			try {
				if(is != null){
					is.close();
					is   = null;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static String getFilePath(ChattingRecord chat, String httpUrl){
		String filepath 		= "";
		String type				= chat.type;
		if(type.equals("1"))
			filepath			= Globals.FILE_PATH_IMAGE;
		if(type.equals("2"))
			filepath			= Globals.FILE_PATH_VIDEO;
		if(type.equals("3"))
			filepath			= Globals.FILE_PATH_AUDIO;
		String fname			= chat.fname;
		if(fname  == null)
			return "";
		if(fname.lastIndexOf("/")  != -1)
			fname = fname.substring(fname.lastIndexOf("/") + 1);
		filepath			   += MD5.toMD5(httpUrl) + fname;
		return filepath;
	}
	
	private static void setConn(HttpURLConnection conn) throws IOException{
//		conn.connect();
		conn.setRequestMethod("GET");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setReadTimeout(TIMEOUT);
	}
}
